import React from 'react';
import {Toast} from 'antd-mobile';
import {phoneSystem} from 'UTIL/commonUtil';

export default function client() {
	let native = {};

	let W = window;

	//回调缓存
	native.call = function(option){
		if(!option.fun){
			return;
		}
		var random = parseInt(Math.random()*10000);
		//alert(random)
		var instance = option.fun+'@'+new Date().getTime()+random;

		if(!W.callbackPool){
			W.callbackPool={};
		}
		if(option.callBack){
			W.callbackPool[instance] = option.callBack;
			W["instance"] = instance;
		}else{
			W["instance"] = instance;
		}

		var def = {
			'fun':'',
			'param':{},
			'url':'',
			'callBack':'',
			'instance':instance
		};

		def = $.extend(def, option);

		def.callBack = 'native.mainCallback';
		if(phoneSystem() == "android"){
			def = JSON.stringify(def);
		}

		try{
			if(phoneSystem() == "android"){
				return W.SysClientJs[option.fun](def);
			}else{
				return W.webkit.messageHandlers.iOS.postMessage(def);
			}
		}catch(e){
			//console.log(e)
		}
	};
    native.mainCallback = function(res){
        try{
        	if(res){
        		var data = res;
	            var reg = /^[\{]{1}[\w\W]+[\}]{1}$/;

	            if(typeof res == 'string' && reg.test(res)){
	                res = res.replace( /[\s\/]/g,"");
	                data = JSON.parse(res);
	            }
	            if(data.instance){
	                return W.callbackPool[data.instance](data);
	            }
        	}

        }catch(e){
        	//alert(e)
        }
    };

	window.native ={
		...native,
		...window.native
	};
};



